<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkDepartment\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkDepartment\Contract\WorkDepartmentContract;
use MoChat\App\WorkEmployee\Constants\Status;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 组织管理- 查看人员列表.
 *
 * Class DepartmentEmployee.
 * @Controller
 */
class DepartmentEmployee extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var WorkDepartmentContract
     */
    private $workDepartmentService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    private $workEmployeeService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workDepartment/departMentEmployee", methods="get")
     * @return array 返回数组
     */
    public function handle(): array
    {
        # # 参数验证
        $this->validated($this->request->all());

        // 接收参数
        $params['searchKeyWords'] = $this->request->input('searchKeyWords');

        $corpId = user()['corpIds'];
        if (count($corpId) > 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '请先选择企业');
        }

        // 验证参数
        $this->validated($params);

        // 主部门信息
        $department = $this->workDepartmentService->getWorkDepartmentsByCorpIdParentId(user()['corpIds'][0], 0, ['id', 'name', 'parent_id']);
        // 主部门员工
        $columns = [
            'id',
            'name',
            'wx_user_id',
            'avatar',
            'alias',
            'main_department_id',
        ];
        $employees = $this->workEmployeeService->getWorkEmployeeByCorpIdLimit((int) user()['corpIds'][0], 200, (int) Status::ACTIVE, $columns);
        foreach ($employees as &$item) {
            $item['employeeId'] = $item['id'];
            $item['avatar'] = file_full_url($item['avatar']);
            $item['departmentName'] = $department[0]['name'];
        }
        unset($item);
        // 主部门企业员工
        $department[0]['employee'] = $employees;

        // 子部门信息
        $department[0]['childDepartment'] = $this->recursion($department[0]['id'], $columns, []);
        return $department;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }

    /**
     * 无限递归查询.
     */
    private function recursion(int $id, array $columns, array $child): array
    {
        // 子部门信息
        $childDepartment = $this->workDepartmentService->getWorkDepartmentsByParentId($id);
        // 处理子部门员工
        foreach ($childDepartment as &$v) {
            $employee = $this->workEmployeeService->getWorkEmployeeByCorpIdMainDepartmentId((int) user()['corpIds'][0], $v['id'], 200, (int) Status::ACTIVE, $columns);
            foreach ($employee as &$val) {
                $val['employeeId'] = $val['id'];
                $val['avatar'] = file_full_url($val['avatar']);
                $val['departmentName'] = $v['name'];
            }
            unset($val);
            $v['employee'] = $employee;
            $v['childDepartment'] = $this->recursion($v['id'], $columns, $child);
        }
        unset($v);
        if (count($childDepartment) > 0) {
            $child = $childDepartment;
        }
        return $child;
    }

    /**
     * 获取成员信息.
     * @param $params
     * @return array
     */
    private function getEmployee($params)
    {
        $columns = [
            'id',
            'name',
            'wx_user_id',
            'avatar',
            'alias',
            'main_department_id',
        ];

        if (! empty($params['searchKeyWords'])) {
            $employee = $this->workEmployeeService->getWorkEmployeesByCorpIdNameStatus(
                (int) user()['corpIds'][0],
                $params['searchKeyWords'],
                (int) Status::ACTIVE,
                $columns
            );
        } else {
            $employee = $this->workEmployeeService->getWorkEmployeesByCorpIdStatus(user()['corpIds'][0], (int) Status::ACTIVE, $columns);
        }

        array_walk($employee, function (&$item) {
            $item['employeeId'] = $item['id'];
            $item['avatar'] = file_full_url($item['avatar']);
        });

        return $employee;
    }
}
